<?php
namespace app\common\model;

use think\facade\Session;
use think\facade\Db;
use hema\wechat\Driver;

/**
 * 小程序模型
 */
class Applet extends BaseModel
{
    //定义表名
    protected $name = 'applet';

    // 定义主键
    protected $pk = 'applet_id';

    // 追加字段
    protected $append = ['new_code'];

    /**
     * 关联模板表
     */
    public function template()
    {
        return $this->belongsTo('app\\common\\model\\Template','app_type','app_type');
    }

    /**
     * 关联模板表
     */
    public function tpl()
    {
        return $this->belongsTo('app\\common\\model\\AppletTpl');
    }

    /**
     * 检测模板版本
     */
    public function getNewCodeAttr($value,$data)
    {
    	//授权中的进行检测
        if($data['status']==1){
        	//获取最新模板代码
        	if($code = TemplateCode::getNew($data['app_type'])){	//有代码
        		//获取最新发布记录
	        	if($tpl = AppletTpl::getNew($data['applet_id'])){
	        		if($tpl['applet_tpl_id'] > $data['applet_tpl_id']){
	        			//有新版本
	        			return ['value' => 1, 'text' => '发布' . $code['user_version']];
	        		}else{
	        			if($tpl['status']['value'] == 1 OR $tpl['status']['value'] == 5 ){
	        				//被拒绝和撤回可重新发布
	        				return ['value' => 1, 'text' => $tpl['status']['text'] . '(重发)'];
	        			}elseif($tpl['status']['value'] != 2){
	        				//其它状态不可点击
	        				return ['value' => 0, 'text' => $tpl['status']['text']];
	        			}
	        		}
	        	}else{
	        		return ['value' => 1, 'text' => '发布' . $code['user_version']];
	        	}
        	}
        }
    }
	
    /**
     * 微信头像
     */
    public function getHeadImgAttr($value)
    {
        empty($value) && $value = base_url() . 'assets/img/no_pic.jpg';
        return $value;
    }
	
	/**
     * 账号来源
     */
    public function getSourceAttr($value)
    {
        $status = [10 => '自注', 20 => '平台'];
        return ['text' => $status[$value], 'value' => $value];
    }

    /**
     * 是否授权
     */
    public function getStatusAttr($value)
    {
        $status = ['否','是'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 门店类型
     */
    public function getShopModeAttr($value)
    {
		$status = [10 => '单', 20 => '多'];
        return ['text' => $status[$value], 'value' => $value];
    }
	
	/**
     * 到期时间
     */
    public function getExpireTimeAttr($value)
    {
		$day = round(($value - time()) / 86400);
        return ['text' => date("Y-m-d", $value), 'value' => $value, 'day' => $day];
    }
	
	/**
     * 获取列表 
     *  $type 0全部 10已授权 20授权已到期
     */
    public function getList($type = 0, $user_id = 0, $agent_id = 0)
    {
		// 筛选条件
        $filter = [];
        $user_id > 0 && $filter['user_id'] = $user_id;
        $agent_id > 0 && $filter['agent_id'] = $agent_id;
        if($type > 0){
        	$filter['status'] = 1;
        	$type == 20 && $filter['expire_time'] = ['<',time()];
        }
        // 执行查询
        return $this->with(['template','tpl'])
            ->where($filter)
            ->order('applet_id','desc')
            ->paginate(['list_rows'=>15,'query' => request()->param()]);
    }

    /**
     * 获取详情
     */
    public static function detail()
    {
        return self::find();
    }

    /**
     * 获取小程序信息 - 回调接口
     */
    public static function getApplet(array $filter = [])
    {
        return self::withoutGlobalScope()->where($filter)->find();
    }

    /**
     * 创建小程序
     * @param [type] $data     数据
     * @param string $dataType 数据类型 app=用户新增,apply=平台入驻
     */
    public function add(array $data, string $dataType='app')
    {
    	$pay = 0;//支付费用
    	if($dataType=='app'){
			if(!is_phone($data['phone'])){
				$this->error = '手机号码错误';
	            return false;	
			}
			$template = Template::get($data['template_id']);//获取版本详情
			$user = User::get($data['user_id']);//获取商户详情
			$agent_price = 0;//代理费用
			//判断是否试用
			if($data['year']>0){
				//计算费用
				if($data['shop_mode']==10){
					//单商户
					$pay = $template['buy_single'][$data['year']];
					$agent_price = $template['single_price']*$data['year'];
				}
				if($data['shop_mode']==20){
					//多商户
					$pay = $template['buy_many'][$data['year']-1];
					$agent_price = $template['many_price']*$data['year'];
				}
				$expire_time = strtotime('+'.$data['year'].'year');//计算到期时间
			}else{
				$expire_time = time()+$template['trial_day']*3600*24;//计算到期时间
			}
			$data['expire_time'] = $expire_time;
			$data['app_type'] = $template['app_type'];
		}
		// 开启事务
        Db::startTrans();
        try {
			//扣费
			if($dataType=='app' AND $pay>0){
				$order_list = [];
				array_push($order_list,[
					'user_type' => 20,
					'action' => 20,//扣减
					'order_no' => order_no(),
					'money' => $pay,
					'pay_status' => 20,
					'pay_time' => time(),
					'remark' => '购买小程序模板',
					'user_id' => $data['user_id']
				]);
				//用户扣费
				$money = $user['money']-$pay;//计算扣除后的余额
				$user->money = ['dec',$pay];
				$user->save();
				//代理分账
				if($data['agent_id']>0){
					//代理分红
					$agent = User::getUser(['user_id' => $data['agent_id']]);
					$agent->money = ['inc',$pay-$agent_price];
					$agent->save();
					array_push($order_list,[
						'user_type' => 20,
						'action' => 10,//增加
						'order_no' => order_no(),
						'money' => $pay-$agent_price,
						'pay_status' => 20,
						'pay_time' => time(),
						'remark' => '代理分账',
						'user_id' => $data['agent_id']
					]);						
				}
				//添加流水记录
				$model = new Recharge;
				$model->saveAll($order_list);
			}
			// 添加小程序记录
			$this->save($data);
			// 新增小程序diy配置
			$Page = new Page;
			$Page->insertDefault($this->applet_id,$data);
			// 新增默认门店
			$Shop = new Shop;
			$Shop->insertDefault($this->applet_id,$data);

			Db::commit();
			if($dataType=='app'){
				if($pay>0){
					//账户资金变动提醒
					sand_account_change_msg('购买小程序模板',$pay,$money,$data['user_id']);
				}else{
					//试用申请成功通知
					sand_testing_msg('小程序模板',$expire_time,$data['user_id']);
				}
			}
            return $this->applet_id;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
    }

    /**
     * 删除数据
     */
    public function remove($applet_id)
    {
    	$filter['applet_id'] = $applet_id;
		// 开启事务
        Db::startTrans();
        try {
			$this->clear($applet_id);
        	Wechat::withoutGlobalScope()->where($filter)->delete();
			Page::withoutGlobalScope()->where($filter)->delete();
			//清除门店记录
            $shopId = (new Shop)->withoutGlobalScope()->where($filter)->column('shop_id');
            for($n=0;$n<sizeof($shopId);$n++){
                (new Shop)->remove($shopId[$n],true);
            }
            //清除订单记录
            $orderId = (new Order)->withoutGlobalScope()->where($filter)->column('order_id');
            for($n=0;$n<sizeof($orderId);$n++){
                (new Order)->remove($orderId[$n]);
            }
			$this->withoutGlobalScope()->where($filter)->delete();
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
	}

	/**
     * 清除数据
     */
    public function clear($applet_id)
    {
    	$filter['applet_id'] = $applet_id;
		// 开启事务
        Db::startTrans();
        try {
        	SignLog::withoutGlobalScope()->where($filter)->delete();
			Coupon::withoutGlobalScope()->where($filter)->delete();
			AppletTpl::withoutGlobalScope()->where($filter)->delete();
			Apply::withoutGlobalScope()->where($filter)->delete();
			AppletName::withoutGlobalScope()->where($filter)->delete();
			RechargePlan::withoutGlobalScope()->where($filter)->delete();
			Spec::withoutGlobalScope()->where($filter)->delete();
			SpecValue::withoutGlobalScope()->where($filter)->delete();
			Setting::withoutGlobalScope()->where($filter)->delete();
			UploadFile::withoutGlobalScope()->where($filter)->delete();
			UploadGroup::withoutGlobalScope()->where($filter)->delete();
			Address::withoutGlobalScope()->where($filter)->delete();
			Help::withoutGlobalScope()->where($filter)->delete();
			User::withoutGlobalScope()->where($filter)->delete();
			$model = new Wechat;
        	$model->clear($applet_id);        	
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
	}

    /**
     * 更新小程序设置
     * @param string $dataType 数据类型 app=用户更新,apply=新注册更新
     */
    public function edit(array $data, string $dataType = 'app')
    {
    	if($dataType == 'app'){
	        $wx = new Driver;
	        //添加服务器域名
	        if(!empty($data['api_domain']) AND $this->api_domain != $data['api_domain']){
	            $result = $wx->setServeDomain($this->applet_id,$data['api_domain']);
	            if($result['errcode'] != 0){
	                $this->error = '服务器域名设置失败！code：'.$result['errcode'].',msg：'.$result['errmsg'];
	                return false;
	            }
	        }
	        if(!empty($data['signature']) AND $this->signature != $data['signature']){
	            $result = $wx->setSignature($this->applet_id,$data['signature']);
	            if($result['errcode'] != 0){
	                $this->error = '简介设置失败！code：'.$result['errcode'].',msg：'.$result['errmsg'];
	                return false;
	            }
	        }
        }
        return $this->save($data) !== false;
    }

     /**
     * 一键登录应用
     */
    public function login()
    {
		$user = User::getUser(['user_id' => $this->user_id]);
        Session::set('hema_store',[
        	'user' => $user,
        	'applet' => $this,
        	'is_login' => true,
			'is_admin' => true,
        ]);
        return '/store/' . $this->app_type . '.applet/index';
    }

	/**
     * 上传小程序模板
     */
    public function publish()
    {
    	//获取最新版本
		$tpl = TemplateCode::getNew($this->app_type);
		//执行上传代码模板
		$wx = new Driver;
		$result = $wx->publish($this, $tpl);
		if($result['errcode'] != 0){
			$this->error = 'code：' . $result['errcode'] . '，msg：' . $result['errmsg'];
            return false;
		}	
		$result = $wx->submitAudit($this->applet_id);	
		if($result['errcode'] != 0){
			$this->error = 'code：' . $result['errcode'] . '，msg：' . $result['errmsg'];
            return false;
		}
		//添加商户发布的模板记录
		$model = new AppletTpl;
		return $model->save([
					'template_code_id' => $tpl['template_code_id'],
					'auditid' => $result['auditid'],	//获取审核编号
					'applet_id' => $this->applet_id
				]);

	}


























	
	/**
     * 根据条件统计数量
     */
    public static function getCount($agent_id = 0)
    {
		$self = new static;
        $count = array();
		//全部统计
		$count['all']['all'] = self::withoutGlobalScope()->count();//全部数量
		$count['all']['agent'] = self::withoutGlobalScope()->where(['agent_id' => ['>',0]])->count();//全部代理数量
		$count['all']['normal'] = self::withoutGlobalScope()->where(['status' => 1])->count();//全部已授权
		$count['all']['warn'] = self::withoutGlobalScope()->where(['expire_time' => ['<',time()+30*86400]])->count();//全部将到期
		$count['all']['ends'] = self::withoutGlobalScope()->where(['expire_time' => ['<',time()]])->count();//全部已到期
		$count['agent']['all'] = self::withoutGlobalScope()->where(['agent_id' => $agent_id])->count();//所属代理数量
		$count['agent']['normal'] = self::withoutGlobalScope()->where(['agent_id' => $agent_id,'status' => 1])->count();//所属代理已授权
		$count['agent']['warn'] = self::withoutGlobalScope()->where(['agent_id' => $agent_id,'expire_time' => ['<',time()+30*86400]])->count();//所属代理将到期
		$count['agent']['ends'] = self::withoutGlobalScope()->where(['agent_id' => $agent_id,'expire_time' => ['<',time()]])->count();//所属代理已到期
		//今天统计
		$star = strtotime(date('Y-m-d 00:00:00',time()));
		$count['today']['all'] = self::withoutGlobalScope()->where(['create_time' => ['>',$star]])->count();//全部数量
		$count['today']['agent'] = self::withoutGlobalScope()->where(['agent_id' => $agent_id,'create_time' => ['>',$star]])->count();//所属代理数量
		//昨天统计
		$star = strtotime("-1 day");
		$end = strtotime(date('Y-m-d 00:00:00',time()));
		$count['today2']['all'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today2']['agent'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//前天统计
		$star = strtotime("-2 day");
		$end = strtotime("-1 day");
		$count['today3']['all'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today3']['agent'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//-4天统计
		$star = strtotime("-3 day");
		$end = strtotime("-2 day");
		$count['today4']['all'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today4']['agent'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//-5天统计
		$star = strtotime("-4 day");
		$end = strtotime("-3 day");
		$count['today5']['all'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today5']['agent'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//-6天统计
		$star = strtotime("-5 day");
		$end = strtotime("-4 day");
		$count['today6']['all'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today6']['agent'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//-7天统计
		$star = strtotime("-6 day");
		$end = strtotime("-5 day");
		$count['today7']['all'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['today7']['agent'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//本月统计 
		$end = mktime(0,0,0,date('m'),1,date('y')); 
		$count['month']['all'] = self::withoutGlobalScope()->where('create_time','>',$end)->count();//全部数量
		$count['month']['agent'] = self::withoutGlobalScope()->where('create_time','>',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		//上月统计  
		$star = mktime(0,0,0,date('m')-1,1,date('y'));
		$count['month2']['all'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->count();//全部数量
		$count['month2']['agent'] = self::withoutGlobalScope()->where('create_time','>',$star)->where('create_time','<',$end)->where(['agent_id' => $agent_id])->count();//所属代理数量
		return $count;
    }
}
